<?php

/**
 * @author Victor Cardenas
 * Clase para crear elementos de seleccion de fecha en formularios
 *
 */
class App_Form_Element_Datepicker extends Zend_Form_Element_Text {
    
    private $_autoadd;
    
    /**
     * Text input para seleccion de fechas en formularios
     * @param string $spec
     * @param bool $autoaddjs
     * @param array $options
     */
    public function __construct($spec, $autoaddjs=true, $options = null) {
        $this->_type = "Zend_Form_Element_Text";
        parent::__construct($spec, $options);
        $this->_autoadd = $autoaddjs;
    }
    
    /**
     * Set element value
     *
     * @param  mixed $value
     * @return Zend_Form_Element
     */
    public function setValue($value) {
        if(is_string($value)) {
            $value = new Zend_Date($value);
        }
//        Zend_Debug::dump($value);
        if (!empty($value))
        parent::setValue($value->toString(Zend_Registry::get("appConfig")->fecha_formato_mostrar));
    }
    
    public function render(Zend_View_Interface $view = null) {
        $content = parent::render($view);
        if(empty($content)) {
            return $content;
        }
        
        //Zend_Debug::dump($this->renderViewHelper(), "helper");
        $input = $this->renderViewHelper();
        $result  = "<div class=\"input-group\">\n";
        $result .= "{$input}\n";
        $result .= "<span class=\"input-group-btn\">\n";
        $result .= "<button id=\"{$this->getId()}-btncalendar\" class=\"btn btn-sm btn-default\" type=\"button\"><span class=\"glyphicon glyphicon-calendar\"></span></button>\n";
        $result .= "</span>\n";
        $result .= "</div>\n";
        
        $result .= "<script type=\"text/javascript\">";
        if($this->_autoadd) {
            $result .= "$(function() {";
            $result .= "$(\"#{$this->getId()}\").datepicker();";
            $result .= "});";
        }
        $result .= "$(\"#{$this->getId()}-btncalendar\").click(function() {";
        $result .=   "$(\"#{$this->getId()}\").datepicker('show');";
        $result .= "});";
        $result .= "</script>";
        
        return preg_replace("/<input.*?>/", $result, $content);
    }
    
}
